import uuid

from django.http import HttpResponse, response, JsonResponse
from django.shortcuts import render, redirect
from redis import StrictRedis, ConnectionPool

from user.models import User


def login_post(request):
    pool = ConnectionPool(host='localhost', port=6379, db=0, password='')
    redis = StrictRedis(connection_pool=pool, decode_responses=True)
    obj = redirect('/login')
    if request.COOKIES.get('login-cookie'):
        login_cookie = request.COOKIES.get('login-cookie')
        user_cookie = str(login_cookie).split('/')
        format_redis = redis.get(user_cookie[0]).decode()
        if format_redis == user_cookie[1]:
            redis.setex(user_cookie[0], 60 * 60 * 24 * 7, user_cookie[1])
            obj.set_cookie('login-cookie', user_cookie[0] + '/' + user_cookie[1], path='/', max_age=60 * 60 * 24 * 7)
            obj = redirect('/')
        else:
            obj.set_cookie('login-cookie', user_cookie[0] + '/' + user_cookie[1], path='/', max_age=0)
            redis.delete(user_cookie[0])
    else:
        username = request.POST['username']
        password = request.POST['password']
        res = User.objects.filter(username=username, password=password)
        arr = []
        for i in res:
            content = {'username': i.username, 'password': i.password}
            arr.append(content)
        if arr.__len__() != 0:
            obj = redirect('/')
            u = uuid.uuid1()
            str1 = str(username)
            str1 = str1 + '/'
            str2 = str(u)
            str1 = str1 + str2
            redis.set(username, u, ex=60 * 60 * 24 * 7)
            obj.set_cookie('login-cookie', str1, path='/', max_age=60 * 60 * 24 * 7)

    return obj


def exit_login(request):
    pool = ConnectionPool(host='localhost', port=6379, db=0, password='')
    redis = StrictRedis(connection_pool=pool, decode_responses=True)
    login_cookie = request.COOKIES.get('login-cookie')
    user_cookie = str(login_cookie).split('/')
    obj = redirect('/')
    obj.set_cookie('login-cookie', user_cookie[0] + '/' + user_cookie[1], path='/', max_age=0)
    redis.delete(user_cookie[0])
    return obj


def register(request):
    username = request.POST['username']
    password = request.POST['password']
    user = User(username=username, password=password)
    user.save()
    obj = redirect('/')
    return obj


def get_username(request):
    username = request.POST['value']
    res = User.objects.filter(username=username)
    arr = []
    for i in res:
        content = {'username': i.username}
        arr.append(content)
    data = {'msg': 'true'}
    if arr.__len__() != 0:
        data['msg'] = 'false'
    return JsonResponse(data)
